package com.mioto.ld.communication.websocket.util;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author mioto-qinxj
 * @date 2024/5/16
 * @desc
 */
@Slf4j
public class WsChannelUtil {
    /**
     * websocket连接通道缓存
     * key - clientId
     * value - channel
     */
    private static ConcurrentMap<String, Channel> websocketChannelCache = new ConcurrentHashMap<>(8);

    public static final String WEB = "web";
    public static final String ANDROID = "android";
    public static final String IOS = "ios";

    public static String buildAppClientId(Integer userId){
        return StrBuilder.create(userId.toString()).append(StrUtil.UNDERLINE).append(ANDROID).toString();
    }
    /**
     * 根据客户端唯一标识获取连接通道列表
     * @param clientId
     * @return
     */
    public static List<Channel> get(String clientId){
        List<Channel> channels = new ArrayList<>(2);
        for (Map.Entry<String, Channel> stringChannelEntry : websocketChannelCache.entrySet()) {
            if (stringChannelEntry.getKey().indexOf(clientId) == 0){
                channels.add(stringChannelEntry.getValue());
            }
        }
        return channels;
    }

    /**
     * 缓存WEBSOCKET连接通道
     * @param ctx
     */
    public static void put(ChannelHandlerContext ctx){
        websocketChannelCache.put(buildCacheKey(ctx), ctx.channel());
    }

    /**
     * 删除连接通道
     * @param ctx
     */
    public static void remove(ChannelHandlerContext ctx){
        if (isExist(ctx)){
            websocketChannelCache.remove(buildCacheKey(ctx));
        }
    }

    /**
     * 根据key判断是否存在缓存通道
     * @return
     */
    public static boolean isExist(ChannelHandlerContext ctx){
        try {
            if (websocketChannelCache.containsKey(buildCacheKey(ctx))){
                return true;
            }
        }catch (NullPointerException e){
            log.error("channel attribute key clientId is null");
        }
        return false;
    }

    /**
     * 获取连接通道自定义属性
     * @param ctx
     * @return
     */
    public static Attribute getAttr(ChannelHandlerContext ctx){
        return ctx.channel().attr(AttributeKey.valueOf("clientId"));
    }

    /**
     * 创建缓存键
     * @param ctx
     * @return
     */
    private static String buildCacheKey(ChannelHandlerContext ctx) throws NullPointerException{
        return  StrBuilder.create(getAttr(ctx).get().toString())
                .append(StrUtil.UNDERLINE)
                .append(ctx.channel().id().asShortText()).toString();
    }
}
